<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <h3 class="title">后台管理系统</h3>
      <el-form-item prop="username">
        <img src="../../assets/images/userIcon.png" alt="user">
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <el-form-item prop="password">
        <img src="../../assets/images/passwordIcon.png" alt="password">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-form-item prop="verificationCode" id="verificationCode">
        <el-input
          ref="verificationCode"
          v-model="loginForm.verificationCode"
          placeholder="请输入验证码"
          name="verificationCode"
          type="text"
          tabindex="3"
          maxlength="4"
          @keyup.enter.native="handleLogin"
        />
        <img id="checkMa" @click="changeCheckCode" :src="imgSrc" alt="checkMa" />
      </el-form-item>
      <el-button :loading="loading" type="primary" id="login" @click.native.prevent="handleLogin">登 录</el-button>
    </el-form>
  </div>
</template>

<script>
  import request from '../../utils/request.js'
  import {setToken} from '../../utils/auth'
  import {baseUrl} from '../../settings'
  import {Message} from 'element-ui'
export default {
  name: 'login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value==="" || value===null || value===undefined) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value==="" || value===null || value===undefined) {
        callback(new Error('密码不能为空'))
      }else if(value.length < 6) {
        callback(new Error('密码长度不能小于6位'));
      }
      else {
        callback()
      }
    };
    const validateVerificationCode = (rule, value, callback) => {
      if (value==="" || value===null || value===undefined) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    };
    return {
      loginForm: {
        username: '',
        password: '',
        verificationCode:''//文本框输入的验证码
      },
      imgSrc:baseUrl+'kaptcha',
      verificationCodeList:[],//数字字母组合
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        verificationCode: [{ required: true, trigger: 'blur', validator: validateVerificationCode }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    //更新验证码
    changeCheckCode(){
      this.imgSrc=baseUrl+"kaptcha?n="+new Date().getTime();
    },
    // 密码的显示与否
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 点击登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
            let that=this;
            request({
              method: 'post',
              url: 'agent/agent/login',
              params: {
                userName: that.loginForm.username.trim(),
                password: that.loginForm.password,
                code:that.loginForm.verificationCode
              }
            }).then(function (res) {
              if(res.code===200){
                that.getUserInfo();
              }else{
                that.changeCheckCode();
              }
            }).catch(function (error) {
                console.log(error);
              });
          }
      })
    },
    //获取用户信息
    getUserInfo(){
      let that=this;
      request({
        method: 'get',
        url: 'agent/agent/info',
      }).then(function (res) {
        if(res.code===200){
          sessionStorage.setItem('admin',res.data.name);
          sessionStorage.setItem('recommendUrl',res.data.recommendUrl);
          that.$router.push("/index")
        }else{
          that.n+=1;
        }
      }).catch(function (error) {
        console.log(error);
      });
    }
  }
}
</script>

<style scoped src="../../assets/css/login/login.css">

</style>
